package cn.sc.summer.auth.component;

import cn.sc.summer.constant.token.TokenConstant;
import cn.sc.summer.redis.util.RedisHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 类名：验证失败添加redis锁进行用户锁定
 *
 * @author a-xin
 * @date 2023/11/24 09:59
 */
@Slf4j
@Component
public class AuthenManager implements AuthenticationManager {

    @Value("${token.failLock}")
    private Integer FAIL_LOCK_TIME;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getName();
        String lockKey = TokenConstant.LOCK_USER + name;
        RedisHelper.incr(lockKey, 1);
        RedisHelper.expire(lockKey, FAIL_LOCK_TIME, TimeUnit.HOURS);
        log.error("==> User tel : {}, Login failed number : {}", name, RedisHelper.get(lockKey));
        authentication.setAuthenticated(Boolean.FALSE);
        return authentication;
    }

}
